/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bamboo.drawingkid.helpers;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Image;

import bamboo.drawingkid.Main;

/**
 *
 * @author tkor
 */
public class FileHandler {

    public FileHandler() {
    }

    public static void saveImageToFile(final String filename, final Image image, final SaveFileListener listener) {
        new Thread() {

            public void run() {

                if (filename.length() > 0) {
                    
                    FileConnection con = null;
                    OutputStream out = null;
                    try {
                        con = (FileConnection) Connector.open(System.getProperty("fileconn.dir.photos") + filename + ".bmp");
                        if (con != null) {
                            if(listener != null) {
                            	listener.startSaveFile();
                            	listener.saveFileInProgress(0);
                            }
                            if (con.exists()) {
                                con.delete();
                            }
                            con.create();
                            out = con.openOutputStream();
                            BMPEncoder enc = new BMPEncoder(image);
                            enc.writeImageToFile(out);
                            if(listener != null) {
                            	listener.finishSaveFile();
                            }
                        }
                    } catch (Exception e) {
                        if(listener != null) {
                        	listener.saveFileError();
                        }
                    } finally {
                        try {
                            if(out != null) {
                                out.close();
                            }
                            if(con != null) {
                                con.close();
                            }
                        } catch (IOException io) {
                        }
                    }
                    
                }else {
                    Main.getInstance().showError("Please give filename.");
                }
            }
        }.start();
    }

}
